<template>
    <div class="container">
        <m-header :closeFn="onClose">班次</m-header>
        <div class="main">
            <div class="date-wrap">
                <div class="date-list">
                    <template v-for="(item,index) in dateList">
                        <div :class="['date-item',{active: item.dateStr === dateValue}]" @click="onDateSelect(item.dateStr,item.date)">
                            <p>{{item.dayStr}}</p>
                            <p>{{item.shortDateStr}}</p>
                        </div>
                    </template>
                    <!--<div class="date-item">
                        <p>明天</p>
                        <p>03-18</p>
                    </div>
                    <div class="date-item">
                        <p>后天</p>
                        <p>03-19</p>
                    </div>
                    <div class="date-item">
                        <p>周四</p>
                        <p>03-20</p>
                    </div>
                    <div class="date-item">
                        <p>周五</p>
                        <p>03-21</p>
                    </div>
                    <div class="date-item">
                        <p>周六</p>
                        <p>03-22</p>
                    </div>
                    <div class="date-item">
                        <p>周日</p>
                        <p>03-23</p>
                    </div>-->
                </div>
                <div class="calendar" @click="showCalendar = true">
                    <div>全部<br />日期</div>
                </div>
            </div>
            <div class="list-wrap">
                <m-list :total="total" :cur-num="list.length" v-model="loading" @load="getDataList" :load-end="loadEnd">
                    <div class="item-wrap" v-for="(item,index) in list" :key="index" @click="onSelect(item)">
                        <div class="item-box">
                            <div class="title bold">{{item.shuttle_name}}</div>
                            <div class="info">
                                <div class="h2" v-if="type !== 'tplx002'">{{item.go_departure_time}}出发，{{item.go_arrive_time}}到达</div>
                                <div class="h2" v-if="type !== 'tplx001'">{{item.leave_departure_time}}出发，{{item.leave_arrive_time}}到达</div>
                                <div class="h2 margin-bot10">时段：{{item.service_period}}</div>
                                <div class="h2 margin-bot10">说明：{{item.mark}}</div>
                                <div class="h2 margin-bot10 bold">{{item.sell_dateime_start}}开售</div>
                            </div>
                            <div class="qr">
                                <van-icon name="qr" size="24" @click.stop="previewQr(item.group_qrcode)" />
                                <div>咨询</div>
                            </div>
                        </div>

                    </div>
                </m-list>
            </div>
        </div>

        <van-calendar v-model="showCalendar" :default-date="defDate" color="#25d37e" @confirm="onCalendarConfirm" :show-confirm="false"/>
    </div>
</template>

<script>
  import list from '@/components/list/list';
  import {mapState,mapGetters,mapMutations,mapActions} from 'vuex';
  import {getShuttle} from "../../../request/api";
  import {crtTimeFtt} from "../../../utils/utils";
  import {ImagePreview,Calendar } from 'vant'

  const http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath;

  export default {
    name: "chooseSchedule",
    components: {
      "m-list": list,
      [ImagePreview.Component.name]: ImagePreview.Component,
      [Calendar.name]: Calendar
    },
    /**
     * type: 套票类型
     * goId: 上车上车站点id
     * leaveId: 回程上车站点id
     */
    props: ['type','goId','leaveId'],
    computed: {
      ...mapState({
        schoolId: state => state.school.schoolId
      })
    },
    data() {
      return {
        list: [],
        total: 0,
        limit: 10,
        page:1,
        loading: false,
        loadEnd: true,

        dateList: [],   // 顶部日期列表
        dateValue: '',
        defDate: null,
        showCalendar: false
      }
    },
    methods: {
      getDataList(first){
        let {loadEnd,type} = this,  //当前请求页数
          list = [];
        let obj = {
          school_id: this.schoolId || '',
          stop_id_go: '',
          stop_id_leave: '',
          shuttle_id: '',
          shuttle_type: '定制'
        };
        type !== 'tplx002' && (obj.stop_id_go = this.goId || '')
        type !== 'tplx001' && (obj.stop_id_leave = this.leaveId || '')
        getShuttle(obj).then(res => {
          if (res.errcode !== 0)return;
          let data = res.row;

          this.list = data;
          this.loadEnd = !loadEnd;
          this.total = data.length;
          this.limit = data.length;
        })
      },
      onClose(){
        this.$emit('close');
      },
      onSelect(data){
        let {sell_dateime_end,sell_dateime_start} = data,
          nowTime = new Date().getTime(),
          startTime = sell_dateime_start && new Date(crtTimeFtt(sell_dateime_start,'YYYY/MM/DD HH:mm:ss')).getTime(),
          endTime = sell_dateime_end && new Date(crtTimeFtt(sell_dateime_end,'YYYY/MM/DD HH:mm:ss')).getTime()

        if (startTime <= nowTime && nowTime <= endTime){
          this.$emit('select',data);
        } else {
          this.$Toast('当前时间班车不可售');
        }

      },
      onDateSelect(dateStr,date){
        this.dateValue = dateStr;
        this.defDate = date;
        this.formatDates(dateStr)
      },
      onCalendarConfirm(date){
        let dateValue = crtTimeFtt(date,'YYYY-MM-DD');
        this.dateValue = dateValue;
        this.showCalendar = false;
        this.formatDates(dateValue)
      },
      formatDates(date){
        const today = new Date(),
          todayStr = crtTimeFtt(today,'YYYY-MM-DD'),
          todayTime = new Date(todayStr).getTime(),
          tomorrowStr = crtTimeFtt(new Date(todayTime +  24 * 60 * 60 * 1000),'YYYY-MM-DD'),
          nextdaytomorrowStr = crtTimeFtt(new Date(todayTime +  24 * 60 * 60 * 1000 * 2),'YYYY-MM-DD')
        let length = 15,
          thisDay = date ? new Date(date) : today,
          firstDayTime = thisDay.getTime() - 24 * 60 * 60 * 1000 * (length -1 )/2,
          dateValue = '',
          todayIndex = null;
        if (todayTime > firstDayTime){
          firstDayTime = todayTime;
        }
        dateValue = crtTimeFtt(thisDay,'YYYY-MM-DD')

        let dates = [],
          dayCompare = ['周日','周一','周二','周三','周四','周五','周六',]
        for (let i = 0; i < length; i++){
          let date = new Date(firstDayTime + 24 * 60 * 60 * 1000 * i)
          let dateStr = crtTimeFtt(date,'YYYY-MM-DD'),
            shortDateStr = dateStr.substring(5),
            day = date.getDay(),
            dayStr = dayCompare[day];
          if (todayStr === dateStr){
            dayStr = '今天';
          }
          if (dateStr === tomorrowStr){
            dayStr = '明天';
          }
          if (dateStr === nextdaytomorrowStr){
            dayStr = '后天';
          }
          dates.push({
            dayStr,shortDateStr,dateStr,date
          });
        }
        this.dateList = dates;
        this.dateValue = dateValue;
        this.defDate = thisDay;

        // 滚动到指定位置
        this.$nextTick(()=>{
          const element = document.getElementsByClassName('date-item active');
          element[0].scrollIntoView({ behavior: 'smooth' });
        })
      },

    //  预览图片
      previewQr(url){
        if (!url){
          this.$Toast('当前班车未有群二维码');
          return
        }
        console.log(http + url);
        ImagePreview({
          images: [http + url],
          showIndex: false,
          overlayStyle: {
            "background": "rgba(0,0,0,0.5)"
          }
        });
      }
    },
    mounted(){
      this.formatDates();
    }
  }
</script>

<style scoped lang="less">
    .main{
        display: flex;
        flex-direction: column;

        .date-wrap{
            display: flex;
            background: #fff;
            color: #616161;
            .date-list{
                display: flex;
                flex: 1;
                width: 0;
                overflow-x: auto;
                padding: 0 8px 8px;
                .date-item{
                    padding: 10px;
                    flex-shrink: 0;
                    text-align: center;
                    border-radius: 8px;
                    & > p{
                        font-size: 16px;
                        margin: 0;
                        &:first-of-type{
                            font-size: 14px;
                            margin-bottom: 6px;
                        }
                    }
                    &.active{
                        background: #25d37e;
                        color: #fff;
                    }
                }
            }
            .calendar{
                padding: 10px 12px;
                display: flex;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;
                height: 100%;
                box-shadow: -2px -2px 10px 2px rgba(0, 0, 0, 0.1);
                line-height: 16px;
                font-size: 14px;
            }
        }


        .list-wrap{
            flex: 1;
            height: 100%;
            padding: 10px 0;
            box-sizing: border-box;
            .item-wrap{
                padding: 0 10px;
                .item-box{
                    border-bottom: 1px solid #dedede;
                    padding: 0 15px;
                    background: #fff;
                    border-radius: 2px;
                    position: relative;
                    .qr{
                        padding: 10px;
                        position: absolute;
                        top: 0;
                        right: 0;
                        text-align: right;
                    }

                }
                .title{
                    font-size: 17px;
                    color: #333;
                    padding: 10px 0;
                }
                .h2{
                    color: #333;
                    font-size: 14px;
                    line-height: 21px;
                }
                .bold{
                    font-weight: bold;
                }
                .margin-bot10{
                    margin-bottom: 10px;
                }
            }
        }
    }
</style>
